package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.JsonDO;
import com.qianniu.napi.admin.entity.Reserve;
import com.qianniu.napi.admin.service.IReserveService;
import com.qianniu.napi.common.util.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenxuebin
 * @since 2017-08-09
 */
@RestController
@RequestMapping("/reserve")
public class ReserveController {

    private static final Logger logger = LoggerFactory.getLogger(ReserveController.class);

    @Autowired
    private IReserveService reserveService;

    @RequestMapping("/{roomNo}/{date}/{uid}")
    @ResponseBody
    public JsonDO list(@PathVariable("date") String date, @PathVariable("roomNo") String roomNo
            , @PathVariable("uid") String uid) {
        logger.debug("come to list");

        JsonDO json = new JsonDO();

        List<Reserve> list = reserveService.getReserveList(date, roomNo);
        List<Object> result = new ArrayList<Object>();
        Map<String, Object> temp = new HashMap<String, Object>();
        List<Reserve> arr = new ArrayList<Reserve>();
        String curDate = null;
        if (list == null || list.size() == 0) return json;
        curDate = list.get(0).getStartDate();
        for (Reserve item : list) {

            if (!curDate.equals(item.getStartTime())) {
                temp.put("rdate", curDate);
                temp.put("list", arr);
                result.add(temp);

                temp = new HashMap<String, Object>();
                curDate = item.getStartDate();
                arr = new ArrayList<Reserve>();
                arr.add(item);
            } else {
                arr.add(item);
            }
        }

        if (arr.size() > 0) {
            temp.put("rdate", curDate);
            temp.put("list", arr);
            result.add(temp);
        }
        logger.debug(">>> result=" + JSON.toJSONString(result));

        json.setData(result);
        return json;
    }

    @RequestMapping("/my/{date}/{uid}")
    @ResponseBody
    public JsonDO mylist(@PathVariable("date") String date, @PathVariable("uid") String uid) {

        logger.debug("come to mylist");
        JsonDO json = new JsonDO();

        List<Reserve> list = reserveService.getMyReserveList(date, uid);
        List<Object> result = new ArrayList<Object>();
        Map<String, Object> temp = new HashMap<String, Object>();
        List<Reserve> arr = new ArrayList<Reserve>();
        String curDate = null;
        if (list == null || list.size() == 0) return json;
        curDate = list.get(0).getStartDate();
        for (Reserve item : list) {

            if (!curDate.equals(item.getStartDate())) {
                temp.put("rdate", curDate);
                temp.put("list", arr);
                result.add(temp);

                temp = new HashMap<String, Object>();
                curDate = item.getStartDate();
                arr = new ArrayList<Reserve>();
                arr.add(item);
            } else {
                arr.add(item);
            }
        }

        if (arr.size() > 0) {
            temp.put("rdate", curDate);
            temp.put("list", arr);
            result.add(temp);
        }
        logger.debug(">>> result=" + JSON.toJSONString(result));

        json.setData(result);
        return json;
    }

    @RequestMapping("/cancel/{rid}")
    @ResponseBody
    public JsonDO cancel(@PathVariable("rid") String rid) {

        reserveService.cancelReserve(rid);
        JsonDO json = new JsonDO();
        return json;
    }

    @RequestMapping(value = "/change", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO change(@ModelAttribute Reserve reserve) {

        Map map = new HashMap<String, Object>();
        map.put("id", reserve.getId());
        map.put("startTime", reserve.getStartTime());
        map.put("endTime", reserve.getEndTime());
        map.put("roomNo", reserve.getRoomNo());
        map.put("roomName", reserve.getRoomName());
        map.put("rdate", reserve.getStartDate());

        logger.debug(">>> post data=" + JSON.toJSONString(map));

        reserveService.modifyReserve(map);
        JsonDO json = new JsonDO();
        return json;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO create(@ModelAttribute Reserve reserve) {

        logger.debug(">>> /create post data=" + JSON.toJSONString(reserve));
        JsonDO json = new JsonDO();
        String msg = "预约成功";
        boolean flag = getIntime(reserve.getStartTime()) < getIntime(reserve.getEndTime());
        if (flag) {
            List<Reserve> list = reserveService.getReserveList(reserve.getStartDate(), reserve.getRoomNo());
            String date = TimeUtils.getToday();

            for (Reserve item : list) {
                if (!item.getStartDate().equals(date)) break;

                if ((getIntime(reserve.getStartTime()) >= getIntime(item.getStartTime()) &&
                        getIntime(reserve.getStartTime()) < getIntime(item.getEndTime())) ||
                        (getIntime(reserve.getEndTime()) > getIntime(item.getStartTime()) &&
                                getIntime(reserve.getEndTime()) <= getIntime(item.getEndTime()))

                        ) {
//                    msg = "预约时间与"+item.getStartTime()+"--"+item.getEndTime()+"冲突";
                    msg = "预约时间冲突";
                    flag = false;
                    break;
                }
            }
        }

        if (flag) {
            try {
                reserveService.saveReserve(reserve);
            } catch (Exception e) {
                logger.error("saveReserve error", e);
                msg = "保存预约数据失败";
            }
            json.setMsg(msg);
        } else {
            json.setMsg(msg);
            json.setCode(0);
        }
        return json;
    }


    @RequestMapping("/catelist/{type}/")
    @ResponseBody
    public JsonDO catelist(@PathVariable("type") String type) {

        logger.debug("come to mylist");
        JsonDO json = new JsonDO();

//        json.setData(result);
        return json;
    }

    private int getIntime(String str) {
        if (Strings.isNullOrEmpty(str)) return -1;

        Integer sss = Integer.valueOf(str.replace(":", ""));
        logger.debug("sss=" + sss);
        return sss;
    }

}
